// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package config_api_impl

import (
	"context"

	"gitcode.com/openseaotter/so_proto_gen_go.git/config_api"
	"gitcode.com/openseaotter/so_server/config"
	"gitcode.com/openseaotter/so_server/storage"
)

type ConfigApiImpl struct {
	config_api.UnimplementedConfigApiServer
}

func (apiImpl *ConfigApiImpl) GetDomain(ctx context.Context, req *config_api.GetDomainRequest) (*config_api.GetDomainResponse, error) {
	emptyInfo := &config_api.DomainInfo{}

	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}
	if cfg.SuperToken != "" && req.AccessToken == cfg.SuperToken {
		//do nothing
	} else {
		remoteCfg, ok := cfg.GetRemote(req.RemoteId)
		if !ok {
			return &config_api.GetDomainResponse{
				Code:   config_api.GetDomainResponse_CODE_NO_REMOTE,
				ErrMsg: "鉴权服务器不存在",
				Info:   emptyInfo,
			}, nil
		}
		_, _, err := storage.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
		if err != nil {
			return &config_api.GetDomainResponse{
				Code:   config_api.GetDomainResponse_CODE_NO_PERMISSION,
				ErrMsg: "用户不存在",
				Info:   emptyInfo,
			}, nil
		}
	}

	return &config_api.GetDomainResponse{
		Code: config_api.GetDomainResponse_CODE_OK,
		Info: &config_api.DomainInfo{
			Domain:      cfg.Domain,
			HttpPort:    uint32(cfg.HttpPort),
			EnableHttps: cfg.TlsCertFile != "" && cfg.TlsKeyFile != "",
			HttpsPort:   uint32(cfg.HttpTlsPort),
		},
	}, nil
}
